package com.example.testdiyexceltableheader.demos.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.example.testdiyexceltableheader.demos.excel.HeaderWriteHandler;
import com.example.testdiyexceltableheader.demos.excel.read.TestRowDataListListener;
import com.example.testdiyexceltableheader.demos.model.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ExcelService {

    @Autowired
    DataService dataService;

    public void exportTemp(HttpServletResponse response) throws Exception {

        //定义输出类型
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        //设置响应头和下载保存的文件名      用关键字命名
        String excelName = UUID.randomUUID().toString() + ".xlsx";
        response.setHeader("content-disposition", "attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1"));


        List<Target> headerList = dataService.getHeader();
        Map<String, List<String>> role = dataService.getRole();
        ServletOutputStream outputStream = response.getOutputStream();

        EasyExcel.write(outputStream)
                .sheet(0, "name")
                .registerWriteHandler(new HeaderWriteHandler(headerList, role))
//                .registerWriteHandler(new DiyDropWriteHandler(headerList,role))
                .doWrite(new ArrayList<>());


    }


    private void createExcelHeader(OutputStream outputStream) {


    }


    public void importExcel(MultipartFile file) throws IOException {


        try (InputStream inputStream = file.getInputStream();
             ExcelReader excelReader = EasyExcel.read(inputStream).build()
        ) {


            ArrayList<ReadSheet> readSheets = new ArrayList<>();
            ArrayList<TestRowDataListListener> listListeners = new ArrayList<>();
            for (int i = 0; i < 3; i++) {

                TestRowDataListListener testRowDataListListener = new TestRowDataListListener();
                listListeners.add(testRowDataListListener);
                ReadSheet readSheet = EasyExcel.readSheet(i)
                        .registerReadListener(testRowDataListListener)
                        .build();
                readSheets.add(readSheet);
            }

            excelReader.read(readSheets);

            excelReader.finish();

            System.out.println("testRowDataListListener = " + listListeners);

        }
    }
}
